﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using PearTunes.WEB.Models;

namespace PearTunes.WEB.Controllers
{
    /// <summary>
    /// Controller class for actions involving user accounts.
    /// </summary>
    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            base.Initialize(requestContext);
            
            MembershipService.CreateUser("admin", "adminadmin", "admin@peartunes.com");
            MembershipService.CreateUser("testuser", "testuser", "testuser@peartunes.com");
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        /// <summary>
        /// Shows the login form.
        /// </summary>
        public ActionResult LogOn()
        {
            return View();
        }

        /// <summary>
        /// Signs the user in.
        /// </summary>
        /// <param name="model">The LogOnModel containing the username and password</param>
        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    if ((new UserModel()).ListUsers().Where(u => u.Name == model.UserName).Count() == 0)
                    {
                        ModelState.AddModelError("", "Nem létezik ilyen felhasználó.");
                        return View(model);
                    }
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (Roles.IsUserInRole(model.UserName, "administrator"))
                        return RedirectToAction("../Home/AdminHome");
                    else
                        return RedirectToAction("../Home/UserHome");
                }
                else
                {
                    ModelState.AddModelError("", "Hibás felhasználónév vagy jelszó.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        /// <summary>
        /// Shows the registration form.
        /// </summary>
        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        /// <summary>
        /// Registers a new user and signs them in, redirecting them to their home page.
        /// </summary>
        /// <param name="model">The RegisterModel containing account information for the new user.</param>
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    (new UserModel()).AddUser(model.UserName, model.Email, 0, model.Password);

                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        /// <summary>
        /// Provides a form to change the login password for the logged in user.
        /// </summary>
        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        /// <summary>
        /// Changes the password for the logged in user.
        /// </summary>
        /// <param name="model">The ChangePasswordModel containing the old and the new passwords.</param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }




    }
}
